<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Log;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RequestLogMiddleware implements MiddlewareInterface {
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container) {
        $_ENV['APP_LOG'] = env('APP_LOG', false);
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        $this->requestLog($request);
        return $handler->handle(\Hyperf\Utils\Context::set(ServerRequestInterface::class, $request));
    }

    /**
     * @param ServerRequestInterface $request
     */
    private function requestLog($request) {
        if ($_ENV['APP_LOG'] == 'true') {
            $uri = $request->getUri();
            $headers = $request->getHeaders();
            foreach ($headers as &$v) {
                $v = $v[0];
            }
            // 请求记录
            Log::get('sys')->debug(var_export([
                "type" => $request->getMethod(),
                "url" => "{$uri->getScheme()}://{$uri->getHost()}{$uri->getPath()}?{$uri->getQuery()}",
                'headers' => $headers,
                'cookie' => $request->getCookieParams(),
                'body' => $request->getParsedBody(),
            ], true));
        }
    }
}
